﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using Microsoft.SharePoint;

namespace ipi.MCC.Global
{
    public class MCCData
    {
        public enum ItemType
        {
            ListItem = 0x1,
            DocumentFile = 0x2
        }
                
        public DataTable GetListItemDataTable(int CurrentNodeID, string Source)
        {
            return GetTreeNodeDataTable(CurrentNodeID, Source, ItemType.ListItem);
        }

        public DataTable GetDocumentDataTable(int CurrentNodeID, string Source)
        {
            return GetTreeNodeDataTable(CurrentNodeID, Source, ItemType.DocumentFile);
        }

        #region TreeDocuments
        public static int GetCurrentDocumentCount(int CurrentNodeID)
        {
            int CurrentDocumentCount = 0;

            try
            {
                DataTable dtTreeNode = null;
                dtTreeNode = GetTreeNodeDataTable("<Where><Eq><FieldRef Name=\"" + MCC.Global.Constants.TreePosition_InternalColumnName + "\" /><Value Type=\"MCCTreePosition\">" + CurrentNodeID.ToString() + "</Value></Eq></Where>", ItemType.DocumentFile | ItemType.ListItem);
                if (dtTreeNode != null)
                {
                    CurrentDocumentCount = dtTreeNode.Rows.Count;
                }
            }
            catch (Exception exc)
            {
                Exceptions.HandleException(exc, MethodBase.GetCurrentMethod().ReflectedType, MethodBase.GetCurrentMethod(), LoggingType.Exception);
            }

            return CurrentDocumentCount;
        }

        public static DataTable GetTreeNodeDataTable()
        {
            return GetTreeNodeDataTable("<Where><IsNotNull><FieldRef Name=\"" + MCC.Global.Constants.TreePosition_InternalColumnName + "\" /></IsNotNull></Where>", ItemType.DocumentFile | ItemType.ListItem);
        }
        
        protected static DataTable GetTreeNodeDataTable(int CurrentNodeID, string Source, ItemType itCurrent)
        {                                                   
            DataTable dtTreeNode = null;
            try
            {
                SPWeb spwRoot = SPContext.Current.Site.RootWeb;
                dtTreeNode = GetTreeNodeDataTable("<Where><Eq><FieldRef Name=\"" + MCC.Global.Constants.TreePosition_InternalColumnName + "\" /><Value Type=\"MCCTreePosition\">" + CurrentNodeID.ToString() + "</Value></Eq></Where>", itCurrent);
                if ((dtTreeNode != null) && (dtTreeNode.Rows.Count > 0))
                {
                    DataColumn dcDocIconPath = new DataColumn("DocIconPath", System.Type.GetType("System.String"));
                    dtTreeNode.Columns.Add(dcDocIconPath);
                    DataColumn dcFileURL = new DataColumn("FileURL", System.Type.GetType("System.String"));
                    dtTreeNode.Columns.Add(dcFileURL);
                    DataColumn dcViewPropertiesURL = new DataColumn("ViewPropertiesURL", System.Type.GetType("System.String"));
                    dtTreeNode.Columns.Add(dcViewPropertiesURL);
                    DataColumn dcVersionsURL = new DataColumn("VersionsURL", System.Type.GetType("System.String"));
                    dtTreeNode.Columns.Add(dcVersionsURL);
                    DataColumn dcLinkFilename = new DataColumn("LinkFilename", System.Type.GetType("System.String"));
                    dtTreeNode.Columns.Add(dcLinkFilename);

                    DataView dvResult = new DataView(dtTreeNode, "", "SiteID, WebID, ListID, ID", DataViewRowState.CurrentRows);

                    SPSite spsCurrent = null;
                    SPWeb spwCurrent = null;
                    SPList splCurrent = null;

                    try
                    {

                        foreach (DataRowView row in dvResult)
                        {
                            Guid siteID = new Guid(Convert.ToString(row["SiteID"]));
                            Guid webID = new Guid(Convert.ToString(row["WebID"]));
                            Guid listID = new Guid(Convert.ToString(row["ListID"]));
                            int iListItem = Convert.ToInt32(row["ID"]);

                            if ((spsCurrent == null) || (spsCurrent.ID != siteID))
                            {
                                if (spwCurrent != null)
                                {
                                    spwCurrent.Dispose();
                                }

                                if (spsCurrent != null)
                                {
                                    spsCurrent.Dispose();
                                }

                                spsCurrent = new SPSite(siteID, spwRoot.Site.Zone);
                            }

                            if ((spwCurrent == null) || (spwCurrent.ID != webID))
                            {
                                if (spwCurrent != null)
                                {
                                    spwCurrent.Dispose();
                                }

                                spwCurrent = spsCurrent.OpenWeb(webID);
                            }

                            if (spwCurrent != null)
                            {

                                if ((splCurrent == null) || (splCurrent.ID != listID))
                                {
                                    splCurrent = spwCurrent.Lists[listID];
                                }

                                SPListItem liCurrent = splCurrent.GetItemById(iListItem);

                                if (liCurrent.DoesUserHavePermissions(SPBasePermissions.EditListItems))
                                {
                                    //User hat Änderungsrechte auf Item.
                                }

                                string sDetailViewURL = spwCurrent.Site.MakeFullUrl(splCurrent.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl + "?ID=" + liCurrent.ID + "&Source=" + Source);
                                row.Row[dcViewPropertiesURL] = sDetailViewURL;

                                if (liCurrent.File != null)
                                {
                                    SPFile sfiCurrent = liCurrent.File;

                                    row.Row[dcLinkFilename] = sfiCurrent.Name;
                                    row.Row[dcVersionsURL] = spwCurrent.Site.MakeFullUrl(spwCurrent.ServerRelativeUrl + "/_layouts/Versions.aspx" + "?list=" + liCurrent.ParentList.ID.ToString("B") + "&ID=" + liCurrent.ID + "&FileName=" + sfiCurrent.Url + "&Source=" + Source);
                                    row.Row[dcDocIconPath] = "/_layouts/images/" + sfiCurrent.IconUrl;
                                    row.Row[dcFileURL] = spwCurrent.Site.MakeFullUrl(sfiCurrent.ServerRelativeUrl);
                                }
                                else
                                {
                                    row.Row[dcLinkFilename] = liCurrent.Title;
                                    row.Row[dcVersionsURL] = spwCurrent.Site.MakeFullUrl(spwCurrent.ServerRelativeUrl + "/_layouts/Versions.aspx" + "?list=" + liCurrent.ParentList.ID.ToString("B") + "&ID=" + liCurrent.ID + "&Source=" + Source);
                                    row.Row[dcDocIconPath] = "/_layouts/images/icgen.gif";
                                    row.Row[dcFileURL] = sDetailViewURL;
                                }

                                row.Row.AcceptChanges();
                            }
                        }
                    }
                    finally
                    {
                        if (spwCurrent != null)
                        {
                            spwCurrent.Dispose();
                        }

                        if (spsCurrent != null)
                        {
                            spsCurrent.Dispose();
                        }
                    }

                    dtTreeNode.AcceptChanges();
                }
            }
            catch (Exception exc)
            {
                Exceptions.HandleException(exc, MethodBase.GetCurrentMethod().ReflectedType, MethodBase.GetCurrentMethod(), LoggingType.Exception);
            }

            return dtTreeNode;
        }

        private static DataTable GetTreeNodeDataTable(string sCAML, ItemType itCurrent)
        {
            DataTable dtResult = new DataTable();
            DataColumn dcListID = new DataColumn("ListId", System.Type.GetType("System.String"));
            dtResult.Columns.Add(dcListID);
            DataColumn dcWebID = new DataColumn("WebId", System.Type.GetType("System.String"));
            dtResult.Columns.Add(dcWebID);
            DataColumn dcID = new DataColumn("ID", System.Type.GetType("System.String"));
            dtResult.Columns.Add(dcID);
            DataColumn dcTreePosition = new DataColumn(MCC.Global.Constants.TreePosition_InternalColumnName, System.Type.GetType("System.String"));
            dtResult.Columns.Add(dcTreePosition);
            DataColumn dcTitle = new DataColumn("Title", System.Type.GetType("System.String"));
            dtResult.Columns.Add(dcTitle);
            //DataColumn dcLinkFilename = new DataColumn("LinkFilename", System.Type.GetType("System.String"));
            //dtResult.Columns.Add(dcLinkFilename);
            //DataColumn dcDocIcon = new DataColumn("DocIcon", System.Type.GetType("System.String"));
            //dtResult.Columns.Add(dcDocIcon);
            DataColumn dcSiteID = new DataColumn("SiteID", System.Type.GetType("System.String"));
            dtResult.Columns.Add(dcSiteID);

            try
            {
                SPWeb spwRoot = SPContext.Current.Site.RootWeb;
                WebSettings wsMain = new WebSettings(spwRoot);

                SPSiteDataQuery sdq = new SPSiteDataQuery();
                sdq.ViewFields = "<FieldRef Name=\"ID\"/>" +
                                 "<FieldRef Name=\"" + MCC.Global.Constants.TreePosition_InternalColumnName + "\"/>" +
                                 "<FieldRef Name=\"Title\"/>";
                //"<FieldRef Name=\"LinkFilename\"/>";
                sdq.Webs = "<Webs Scope=\"SiteCollection\" />";
                sdq.Query = sCAML;

                bool bCatchAccessDeniedException = SPSecurity.CatchAccessDeniedException;
                try
                {
                    SPSecurity.CatchAccessDeniedException = false;

                    foreach (string sSiteGuid in wsMain.SitesToSearch)
                    {
                        using (SPSite spsCurrent = new SPSite(new Guid(sSiteGuid)))
                        {
                            if (spsCurrent.ServerRelativeUrl != "/ssp/admin")
                            {
                                SPWeb spwCurrentRoot = spsCurrent.RootWeb;

                                try
                                {
                                    if ((itCurrent & ItemType.DocumentFile) == ItemType.DocumentFile)
                                    {
                                        sdq.Lists = "<Lists BaseType='1' MaxListLimit='0' />";
                                        FillItemDataTable(dtResult, sdq, spsCurrent, spwCurrentRoot);
                                    }

                                    if ((itCurrent & ItemType.ListItem) == ItemType.ListItem)
                                    {
                                        sdq.Lists = "<Lists BaseType='0' MaxListLimit='0' />";
                                        FillItemDataTable(dtResult, sdq, spsCurrent, spwCurrentRoot);
                                    }
                                }
                                catch (UnauthorizedAccessException)
                                {

                                }
                            }
                        }
                    }
                }
                finally
                {
                    SPSecurity.CatchAccessDeniedException = bCatchAccessDeniedException;
                }

                dtResult.AcceptChanges();
            }
            catch (Exception exc)
            {
                Exceptions.HandleException(exc, MethodBase.GetCurrentMethod().ReflectedType, MethodBase.GetCurrentMethod(), LoggingType.Exception);
            }
            return dtResult;
        }

        private static void FillItemDataTable(DataTable dtResult, SPSiteDataQuery sdq, SPSite spsCurrent, SPWeb spwCurrentRoot)
        {
            DataTable dtCurrent = spwCurrentRoot.GetSiteData(sdq);

            if (dtCurrent != null)
            {
                AddSiteIDToDataTable(ref dtCurrent, spsCurrent);
                foreach (DataRow drCurrent in dtCurrent.Rows)
                {
                    dtResult.ImportRow(drCurrent);
                }
            }
        }

        private static void AddSiteIDToDataTable(ref DataTable dtCurrent, SPSite spsCurrent)
        {
            DataColumn dcSiteID = new DataColumn("SiteID", System.Type.GetType("System.String"));
            dtCurrent.Columns.Add(dcSiteID);

            foreach (DataRow drCurrent in dtCurrent.Rows)
            {
                drCurrent[dcSiteID] = spsCurrent.ID.ToString();
            }

            dtCurrent.AcceptChanges();
        }
        #endregion
    }
}
